package com.hss01248.facedetect.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.faceplusplus.api.FaceDetecter;
import com.hss01248.facedetect.FaceCj;
import com.hss01248.facedetect.R;
import com.hss01248.facedetect.utils.LogUtil;
import com.hss01248.facedetect.utils.MyBitmapUtils;
import com.hss01248.facedetect.utils.SelfToastUtil;
import com.hss01248.facedetect.view.FaceMask;
import com.hss01248.facedetect.view.LoadingView;
import com.hss01248.titlebarlib.Titlebar;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class CollectNewActivity extends BaseActivity implements SurfaceHolder.Callback, Camera.PreviewCallback {

    Bitmap bitmap_collect;
    String filePath;
    int caseValue;
    String checkType;
    String typeData;
    String imgUrl;
    String rowKey;
    String barcodeNo;
    String task;
    String certificateTypeStr, humanCrednum, humanName;

    SurfaceView svPreview;
    FaceMask fmMask;
    LoadingView loadingView;
    RelativeLayout root;
    private Camera mCamera;
    private HandlerThread handleThread;
    private Handler detectHandler;
    private int width = 640;
    private int height = 480;
    private FaceDetecter facedetecter;

    Activity activity;
    Titlebar titlebar;
    private ImageView img_collect;
    private Button btn_reTake;
    private Button btn_confirm;
    private TextView tv_message;

    private Bitmap bitmap;
    private Bitmap bitmap1;
    private static String basa64;
    private boolean goToTackPhoto = false;

    private static final String TAG = "PhoneActivity";

    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.2f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调


    /**********************语音合成**********************/
//语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect);

        initView();
    }

    private void initView() {
        //        获取传来的值
        caseValue = getIntent().getIntExtra("caseValue", 0);
        checkType = getIntent().getStringExtra("checkType");
        typeData = getIntent().getStringExtra("typeData");
        imgUrl = getIntent().getStringExtra("imgUrl");
        rowKey = getIntent().getStringExtra("rowKey");
        barcodeNo = getIntent().getStringExtra("barcodeNo");
        task = getIntent().getStringExtra("task");
        certificateTypeStr = getIntent().getStringExtra("certificateTypeStr");
        humanCrednum = getIntent().getStringExtra("humanCrednum");
        humanName = getIntent().getStringExtra("idName");

        svPreview = (SurfaceView) findViewById(R.id.sv_preview_track);
        fmMask = (FaceMask) findViewById(R.id.fm_mask_track);
        root = (RelativeLayout) findViewById(R.id.root);
        titlebar = (Titlebar) findViewById(R.id.titlebar);
        tv_message = (TextView) findViewById(R.id.ca_tv_message);

        img_collect = (ImageView) findViewById(R.id.ca_img_collect);
        btn_reTake = (Button) findViewById(R.id.ca_btn_reTake);
        btn_confirm = (Button) findViewById(R.id.ca_btn_confirm);


        //初始化摄像头
        handleThread = new HandlerThread("dt");
        handleThread.start();
        detectHandler = new Handler(handleThread.getLooper());
        svPreview.getHolder().addCallback(this);
        svPreview.setKeepScreenOn(true);

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        try {
            mCamera = Camera.open(0);
            mCamera.setDisplayOrientation(90);
            Camera.Parameters para = mCamera.getParameters();

            Point showingArea = new Point();
            WindowManager wm = (WindowManager) getSystemService(
                    Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            int screenWidth = display.getWidth();
            int screenHeight = display.getHeight();

            int topHeight = dip2px(CollectNewActivity.this, 25 + 44);//状态栏+titlebar
            showingArea.set(screenWidth, screenHeight - topHeight);

            width = 640;
            height = 480;
            // 预览变形的问题
            Log.e("size", "size w:" + width + "--h:" + height);

            para.setPreviewSize(width, height);
            mCamera.setParameters(para);
        } catch (Exception e) {
            SelfToastUtil.getInstance().show("无法找到摄像头，请确定摄像头已连接");
        }


    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        if (mCamera == null) {
            return;
        }
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.setDisplayOrientation(90);
            mCamera.startPreview();
            mCamera.setPreviewCallback(this);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

        if (mCamera == null) {
            return;
        }
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }


    @Override
    public void onPreviewFrame(byte[] data, final Camera camera) {
        // 这个方法 让数据方向进行调整
        final byte[] datas = rotateYUV420Degree180(data, width, height);

        camera.setPreviewCallback(null);
        if (mCamera == null) return;
        detectHandler.post(new Runnable() {
            @Override
            public void run() {
                coseToBase64(datas, camera);
                try {
                    camera.setPreviewCallback(CollectNewActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        });
    }



    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private byte[] rotateYUV420Degree180(byte[] data, int imageWidth, int imageHeight) {
        byte[] yuv = new byte[imageWidth * imageHeight * 3 / 2];
        int i = 0;
        int count = 0;
        for (i = imageWidth * imageHeight - 1; i >= 0; i--) {
            yuv[count] = data[i];
            count++;
        }
        i = imageWidth * imageHeight * 3 / 2 - 1;
        for (i = imageWidth * imageHeight * 3 / 2 - 1; i >= imageWidth
                * imageHeight; i -= 2) {
            yuv[count++] = data[i - 1];
            yuv[count++] = data[i];
        }
        return yuv;
    }

    //这个方法处理图片 后期需要放在 子线程里面
    private void coseToBase64(byte[] data, Camera camera) {

        try {
            Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = true;
            YuvImage yuvimage = new YuvImage(
                    data,
                    ImageFormat.NV21,
                    previewSize.width,
                    previewSize.height,
                    null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);// 80--JPG图片的质量[0-100],100最高
            final byte[] rawImage = baos.toByteArray();
//        将rawImage转换成bitmap
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;

            bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);

            if (bitmap != null) {
                bitmap1 = MyBitmapUtils.rotateBitmap(bitmap, 270, false);
            }

            //经过测试  bitmap1，不为空的情况下，bitmap_collect为空，是剪裁里面 检查不到人脸，返回为空
            if (bitmap1 != null) {
                bitmap_collect = FaceCj.cutFace(bitmap1, CollectNewActivity.this);

            }


            if (bitmap_collect != null) {

//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        tvTipShow.setText("人脸出现，请点击拍照");
//                    }
//                });
                if (goToTackPhoto) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            img_collect.setImageBitmap(bitmap_collect);
                            basa64 = MyBitmapUtils.bitmapToBase64(bitmap_collect);
                            goToTackPhoto = false;
                        }
                    });
                }

                MyBitmapUtils.saveBitmap(bitmap_collect, new File(Environment.getExternalStorageDirectory().toString() + File.separator + "大漠人脸存储" + File.separator + "zyf.png"));
            }
        } catch (Exception e) {
            LogUtil.v("图片回收异常");
        }
    }

}
